package com.gene.tlonpo.manager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson.JSON;

import com.gene.tlonpo.config.LonpoStaticContext;
import com.gene.tlonpo.config.RedisConfig;
import com.gene.tlonpo.converter.GuardConverter;
import com.gene.tlonpo.guard.Guard;
import com.gene.tlonpo.guard.GuardDistributedInfo;
import com.gene.tlonpo.guard.interf.GuardI;
import com.gene.tlonpo.manager.interf.GuardManagerI;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;

/**
 * @author gene
 * 分布式哨兵管理器
 * 单例
 */
public class GuardDistributedManager implements GuardManagerI {

    public static final GuardDistributedManager INSTANCE = new GuardDistributedManager();

    private final RedisConfig redisConfig = LonpoStaticContext.getRedisConfig();

    @Override
    public void removeGuard(GuardI guardI) {
        //按照同一个bizKey的同一台机器的维度进行移除
        if (!(guardI instanceof GuardDistributedInfo)) {
            throw new RuntimeException(
                    "can not execute timeoutmanager,because of param type is not com.gene.tlonpo.guard.Guard");
        }
        GuardDistributedInfo guard = (GuardDistributedInfo) guardI;
        redisConfig.sDelete(guard.getBizKey(),guard);
    }

    @Override
    public <T extends GuardI> List<T> getGuard(String bizKey) {
        Set<GuardDistributedInfo> infos = redisConfig.sGet(bizKey);
        if (CollectionUtils.isEmpty(infos)){
            return null;
        }
        return Lists.newArrayList((Set<T>) infos);
    }

    @Override
    public void addGuard(GuardI guardI) {
        if (!(guardI instanceof Guard)) {
            throw new RuntimeException(
                    "can not execute timeoutmanager,because of param type is not com.gene.tlonpo.guard.Guard");
        }
        Guard guard = (Guard) guardI;

        //添加到redis
        GuardDistributedInfo distributedInfo = GuardConverter.toGuardDistributed(guard);
        redisConfig.sAdd(distributedInfo.getBizKey(), distributedInfo);
    }


}
